/*
表格页面功能
*/
var handleExcle = function (cfg) {
    var that = this;
    this.utl = {};
    this.utl.Binary = {
        fixdata: function (data) { //文件流转BinaryString
            var o = "",
                l = 0,
                w = 10240;
            for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
            o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
            return o;
        },
        s2ab: function (s) { //字符串转字符流
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
    };

    this.utl.XLSX = {
        wb: null,
        rABS: true,
        import: function (f, c) { //导入根据文件
            var file_ext = that.config.cghz;
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            var oReq = new XMLHttpRequest();
            oReq.open("get", "file/loadExcel?Url=" + that.config.cglj, true);
            oReq.responseType = "arraybuffer";
            oReq.onload = function (oEvent) {
                if (oReq.response.size != 0) {
                    if (file_ext == ".XLS" || file_ext == ".XLSX") {
                        // that.utl.XLSX.wb = XLS.read(btoa(utl.Binary.fixdata(oReq.response)), {
                        //     type: 'base64'
                        // });
                        //     that.utl.XLSX.wb = XLS.read(oReq.response, {
                        //         type: 'array'
                        //     });
                        // } else {
                        	debugger;
                        that.utl.XLSX.wb = XLSX.read(oReq.response, {
                            type: 'array'
                        });
                    }

                    if (c && typeof (c)) {
                        c();
                    }
                } else {
                    // alert("文件不存在");
                }
            };
            oReq.send();
        },
        onImport: function (obj, c) { //导入根据 input file标签
            if (!obj.files) {
                return;
            }
            this.import(obj.files[0], c);
        },
        DoExcelLoad: function (c) { //导入根据 input file标签
            this.import(null, c);
        },
        getSheetsByIndex: function () { //获取数据根据Sheets索引
            var index = 0;

            return XLSX.utils.sheet_to_json(this.wb.Sheets[this.wb.SheetNames[index]]);

        },
        getCharCol: function (n) {
            let temCol = '',
                s = '',
                m = 0
            while (n > 0) {
                m = n % 26 + 1
                s = String.fromCharCode(m + 64) + s
                n = (n - m) / 26
            }
            return s
        },
        export: function (json, title, type) { //导出
            var keyMap = []; //获取keys
            for (k in json[0]) {
                keyMap.push(k);
            }
            var tmpdata = []; //用来保存转换好的json

// json.map(
// 	function(v, i) {
// 		keyMap.map(
// 			function(k, j) {
// 				Object.assign({}, {
// 					v: v[k],
// 					position: (j > 25 ? utl.XLSX.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
// 				})
// 			}
// 		)
// 	}
// ).reduce(function(prev, next) {
// 	prev.concat(next)
// }).forEach(function(v, i) {
// 	tmpdata[v.position] = {
// 		v: v.v
// 	}
// });

            json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
                v: v[k],
                position: (j > 25 ? utl.XLSX.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
            }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
                v: v.v
            });
//json.map(  (v, i) => keyMap.map( (k, j) =>
//	Object.assign({}, {
//	v: v[k],
//	position: (j > 25 ? utl.XLSX.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
//	})
//		)
//).reduce( (prev, next) =>
// 	prev.concat(next)
// ).forEach(
//	function (v, i) {
//	tmpdata[v.position] = {
//	v: v.v}
//	}
//);

//          json.map(function (v, i) { keyMap.map( function (k, j) { Object.assign({}, {
//              v: v[k],
//              position: (j > 25 ? utl.XLSX.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
//          })
//}
//)
//}
//).reduce( function (prev, next) {
//	
// prev.concat(next)
//}
//).forEach( function (v, i) { tmpdata[v.position] = {
//              v: v.v
//          }
//}
//);
            var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10
            var tmpWB = new Object();
            title = title ? title : "mySheet";
            tmpWB.SheetNames = [title];
            tmpWB.Sheets = {};
            tmpWB.Sheets[title] = Object.assign({}, tmpdata, //内容
                {
                    '!merges': json["!merges"],
                    '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域
                });

            var sf = XLSX.write(tmpWB, {
                    bookType: (type == undefined ? 'xlsx' : type),
                    bookSST: false,
                    type: 'binary'
                } //这里的数据是用来定义导出的格式类型
            )
            var buf = new ArrayBuffer(sf.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != sf.length; ++i) view[i] = sf.charCodeAt(i) & 0xFF;

            return new Blob([buf], {
                type: ""
            }); //创建二进制对象写入转换好的字节流
        },
        onExport: function (json, title, type) {
            let xlsblob = this.export(json, title, type);
            var formData = new FormData();

            excel_to_html(xlsblob, true, function (table_str) {
                var table_html = table_str;
                var blob = new Blob([table_html], {type: "text/plain;charset=utf-8"});

                formData.append("cgid", that.config.cgid);
                formData.append("file", xlsblob); //加入文件对象
                formData.append("table_html", blob); //加入文件对象
                formData.append("type", ".xlsx");
                if (that.downloadflag == 1) {
                    that.utl.Download.byObj(xlsblob, "excel.xlsx");
                } else {
                    $.ajax({
                        type: 'POST',
                        url: '/zhyj/cg/uploadFile_cg',
                        contentType: false,
                        processData: false,
                        data: formData,
                        success: function (d) {
                            console.log("save success!");
                            layer.msg("保存成功！");
                            open_parent.slt_ljy = d;
                            send.slt_lj = d;
                            $("#Css" + that.config.cgid + " .show_cgd").empty();
                            $("#Css" + that.config.cgid + " .show_cgd").append(d);
                        },
                        error: function (res) {
                        }
                    });


                }
            });// "<table></table>";        
        },
        exlcw_xe: function (exjson, title, type) {
            let xlsblob = this.export(exjson, title, type);

            excel_to_html(xlsblob, true, function (table_str) {
                var table_html = table_str;
                var blob = new Blob([table_html], {type: "text/plain;charset=utf-8"});

                var formData = new FormData();
                var ex_cgid = createguid();
                var cstid_ex = getQueryString("cstid");
                formData.append("CGID", ex_cgid);
                formData.append("file", xlsblob); //加入文件对象
                formData.append("table_html", blob); //加入表格html文件
                formData.append("type", ".xlsx");
                formData.append("ACHMC", title);
                formData.append("CJR", $.cookie("username"));
                formData.append("CJRID", $.cookie("name"));
                formData.append("JDID", jd_id);
                formData.append("KZM", ".XLSX");
                formData.append("CGFLID", flmc);
                formData.append("CGLX", flmc);
                formData.append("FAID", xm_id);
                formData.append("GQID", gqid);
                formData.append("GROUPID", cstid_ex);
                formData.append("ZYLX", send.zyLX);
                $.ajax({
                    type: 'POST',
                    url: '/zhyj/cg/exlcw_cg',
                    contentType: false,
                    processData: false,
                    data: formData,
                    dataType: 'text',
                    success: function (res) {
                        $("#app").prepend("<div><div class=\"el-card list-group-item img_menu is-hover-shadow\"\n" +
                            "                     >\n" +
                            "                    <div class=\"show1\" style=\"cursor: pointer;\">\n" +
                            "                        <div style=\"height: 100%;width: 100%;display: flex\" class=\"icon\">\n" +
                            "                            <img src=\"image/wrong.png\" class=\"delete-show\"\n" +
                            "                                 title=\"删除\">\n" +
                            "                            <img src=\"image/1downarrow.png\" class=\"down-show\"\n" +
                            "                                 title=\"下移\">\n" +
                            "                            <img src=\"image/1uparrow.png\" class=\"up-show\"\n" +
                            "                                 title=\"上移\">\n" +
                            "                        </div>\n" +
                            "                    </div>\n" +
                            "                    <div class=\"el-card__body-show\" style='padding: 10px'>\n" +
                            "                        <div tag=\"" + ex_cgid + "\" title=\"" + title + "\"  class=\"b\" id=\"Css" + ex_cgid + "\" >\n" +
                            "                            <div style=\"display: none\" class=\"num\">" + ex_cgid + "</div>\n" +
                            "                            <div style=\"display: none\" class=\"kzm\">" + '.XLSX' + "</div>\n" +
                            "                            <div class=\"img_s\" height=\"209px\" width=\"139px\"><div class='show_cgd'><p>" + res + "</p></div>\n" +
                            "<div class=\"cm_mc\"> <p>" + title + "</p></div></div>\n" +
                            "                        </div>\n" +
                            "                    </div>\n" +
                            "                </div></div>");
                        show()
                        layer.closeAll();
                    },
                    error: function (err) {
                    }
                })
            })
        }
    };

    this.utl.Download = {
        byURL: function (url, fileName) { //动态下载
            var tmpa = document.createElement("a");
            tmpa.download = fileName || "下载";
            tmpa.href = url; //绑定a标签
            tmpa.click(); //模拟点击实现下载
        },
        byObj: function (obj, fileName) { //内存二进制数据下载
            this.byURL(URL.createObjectURL(obj), fileName);
            setTimeout(function () { //延时释放
                URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
            }, 100);
        }
    }
    this.utl.Object = {
        reverse: function (obj) { //对象键值倒转
            var o = new Object();
            for (var k in obj) {
                o[obj[k]] = k;
            }
            return o;
        },
        deepCopy: function () { //深拷贝
            let temp = obj.constructor === Array ? [] : {}
            for (let val in obj) {
                temp[val] = typeof obj[val] == 'object' ? deepCopy(obj[val]) : obj[val];
            }
            return temp;
        },
        copyJson: function (o) {
            return JSON.parse(JSON.stringify(o));
        } //拷贝JSON格式
    }

}

handleExcle.prototype.LoadCGXlS = function () {
    var that = this;
    that.utl.XLSX.DoExcelLoad(function () {

        let dataset = that.utl.XLSX.wb.Sheets[that.utl.XLSX.wb.SheetNames[0]];

        var rt = that.utl.XLSX.getSheetsByIndex();

        let data = [];
        let merg = [];
        let chars = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"];
        //dataset.map(function(n){
        //    chars.push(n);
        //})
        if (rt.length > 0) {

            let mgs = dataset["!merges"];

            let size = dataset["!ref"]; //"A1:H25"

            let r_cnt = rt.length;

            if (mgs != null) {
                mgs.map(function (n) {

                    let c = {};

                    c.row = parseInt(n.s.r);
                    c.col = parseInt(n.s.c);

                    c.rowspan = (parseInt(n.e.r) - parseInt(n.s.r));
                    c.colspan = (parseInt(n.e.c) - parseInt(n.s.c));

                    c.rowspan++;
                    c.colspan++;

                    merg.push(c);
                });
            }

            for (let i = 1; i < (r_cnt + 2); i++) {
                let arr = [];
                chars.forEach(function (n) {
                    {
                        let v = dataset[n + i];
                        if (v != null) {
                            arr.push(v.v);
                        } else {
                            arr.push("");
                        }
                    }
                });
                data.push(arr);
            }
        } else {
            let arr = [];
            chars.forEach(function (n) {
                {
                    arr.push("");
                }
            });
            data.push(arr);
        }

        container = document.getElementById('excel');

        hot = new Handsontable(container, {
            data: data,
            manualColumnResize: true,
            rowHeaders: true,
            colHeaders: true,
            minRows: 50,
            colHeaders: true,
            contextMenu: true
        });

        if (merg.length > 0)
            hot.updateSettings({
                mergeCells: merg
            });
    });
}

//显示表格页面
handleExcle.prototype.ShowPage = function () {
    var that = this;
    $(that.config.elmt).empty();
    var pagehead = $('<div class="btn_list" style="width:100%;height:30px;display:none;"></div>');
    $(that.config.elmt).append(pagehead);
    /*var btn_lis = $('<div id="btn_list" style="width:100%;height:30px;margin-left:0px;"></div>')
    $(that.config.elmt).append(btn_lis);*/

    /*var showPl2 = $('<button class="layui-btn" style="width:80px;height:30px;float: right;">结论</button>');
    pagehead.append(showPl2	);*/
    /**
     * 侧边栏
     */

//	var showPl = $('<button class="layui-btn" style="width:80px;height:30px;float: right;margin-left: 10px;">评论</button>');
//	pagehead.append(showPl);
//	var showProp = $('<button class="layui-btn" style="width:80px;height:30px;float: right;">属性</button>');
//	pagehead.append(showProp);

    var pagebody = $('<div style="width:100%;overflow: auto; margin-top: 6px;"></div>');
    $(that.config.elmt).append(pagebody);

    pagebody.height($(that.config.elmt).height() );
    var exel_div = $('<div id="excel" style="width:100%;height:100%;"></div>');
    pagebody.append(exel_div);


    that.ShowProperty();
//that.ShowProperty();
//	showPl.on('click', that.ShowPL);
//	showProp.on('click', that.ShowProperty);

    $("#bc_btn").off().on('click', that.save_btn)
    $("#fsdsy_btn").off().on('click', that.fssy_btn)
    $("#lcw_btn").off().on('click', that.lwsave_btn)
    that.LoadCGXlS();
}